<template>
  <div class="hawkContent">
    <!-- <h4>日期筛选精确到时分秒</h4> -->
    <div class="checkDate">
      <el-date-picker style="float:right;width:390px;height:40px;"
                      v-model="date1" value-format="timestamp" type="daterange"
                      range-separator="至" start-placeholder="开始日期"
                      :picker-options="pickerOptions" end-placeholder="结束日期"
                      @change="changeDate">
      </el-date-picker>
    </div>
    <div class="checkDate">
      <el-radio-group v-model="date2" @change="checkDate"
                      style="float:right;width:390px;">
        <el-radio-button :label="86400000">最近一天</el-radio-button>
        <el-radio-button :label="604800000">最近一周</el-radio-button>
        <el-radio-button :label="2592000000">最近一月</el-radio-button>
        <el-radio-button :label="7776000000">最近三月</el-radio-button>
      </el-radio-group>
    </div>
    <component v-for="item in chartList" :key='item.id'
               :is="componentName(item.type)" :chartTitle="item.name"
               :chartData="item.chartData" :unit="item.unit">
    </component>
  </div>
</template>

<script>
/**
* @author 罗冲
* @description 主机监控数据趋势
* @api 后台接口地址
* @since 2021-11-09
* @update 代码更新时间
* @modifier 修改人
* @bug 无
* @version 版本号 例:v1.0.0
*/
import lineChart from './components/lineChart.vue'
import columnChart from './components/columnChart.vue'

import { getTrendList, getItemById } from '@/api/monitor/hosts/host.js'

export default {
  components: { lineChart, columnChart },
  data () {
    return {
      // 提交信息
      queryInfo: {
        hostId: '',
        date: {
          "beginTime": "",
          "endTime": "",
          "recentlyDay": true,
          "recentlyMonth": true,
          "recentlyThreeMonth": true,
          "recentlyWeek": true
        }
      },
      // 日期数据
      date1: [],
      date2: 86400000,
      // 图表列表
      chartList: [],

      itemsName: {
        "0000": "测试"
      },

      pickerOptions: {
        selectableRange: (() => {
          let data = new Date();
          let hour = data.getHours();
          let minute = data.getMinutes();
          let second = data.getSeconds();
          return [`${hour}:${minute}:${second} - 23:59:59`]
        })(),

        disabledDate (time) {
          var date = new Date();
          date.setFullYear(date.getFullYear() + 2);
          date.setDate(date.getDate() - 1);
          return (time.getTime() > Date.now())
        }
      }

    }
  },
  // DateTimeFormat:''
  // watch: {
  //   date1: {
  //     handler (newV, oldV) {
  //       console.log(newV);
  //       if (!newV) {
  //         return
  //       }

  //       console.log(newV);

  //       beginTime = this.data1[0]
  //       endTime = this.data1[1]



  //     }

  //   }
  // },


  methods: {
    DateTimeFormat () {

      if (this.date1.length > 0) {

        if (this.date1[1] - this.date1[0] > 24 * 60 * 60 * 1000 ) {
           return 'MM-dd'
        }else{
          return 'MM-dd hh:mm'
        }
      }

      if (this.date2 == 86400000) {
        return 'MM-dd hh:mm'
      } else {
        return 'MM-dd'
      }
    },

    // 设置图表类型  0=折线图，1=柱状图
    componentName (type) {
      // console.log(type)
      switch (type) {
        case 0:
          return 'lineChart'
        case 1:
          return 'columnChart'
        default:
          return ''
      }
    },
    // 日期选择
    changeDate () {
      if (!this.date1) {
        return
      }

      console.log(this.date1);

      if (this.date1[0] > this.date1[1]) {
        let t = this.date[0]
        this.date[0] = this.date[1]
        this.date[1] = t
      }
      // 
      // if (this.date1[0] == this.date1[1]) {
        // }
        this.date1[1] = this.date1[1] + 24 * 60 * 60 * 1000

      console.log(this.transformDateFormat(this.date1[0], 'MM-dd hh:mm:ss'));
      console.log(this.transformDateFormat(this.date1[1], 'MM-dd hh:mm:ss'));



      this.queryInfo.date.beginTime = new Date(this.date1[0]);
      this.queryInfo.date.endTime = new Date(this.date1[1]);


      console.log(this.queryInfo);
      this.date2 = '';  //清空单选日期数据

      this.getChartData()

    },
    // 单选近期
    checkDate () {
      // let timestamp = (new Date()).getTime();
      // this.queryInfo.date = [timestamp - this.date2, timestamp];

      let timestamp = (new Date()).getTime(); //获取当前时间时间戳    

      this.queryInfo.date.beginTime = new Date(timestamp - this.date2)  //获取时间段，一小时前到现在
      this.queryInfo.date.endTime = new Date(timestamp)  //获取时间段，一小时前到现在

      this.date1 = [];  //清空日期选择数据

      this.getChartData()
    },

    // 获取图表数据
    async getChartData () {
      console.log(this.queryInfo);
      let ret = await getTrendList(this.queryInfo)

      console.log(ret);

      let showDatas = []
      let obj = null
      let type = 0 // 线状图

      for (let i = 0; i < ret.data.length; i++) {
        let item = ret.data[i]
        if (i == 0 || ret.data[i - 1].itemid != item.itemid) {
          obj = {}
          showDatas.push(obj)
          obj.id = i + 1
          obj.itemid = item.itemid
          obj.name = item.items.name
          // obj.type = Math.floor(Math.random() * 100) % 2 == 0 ? 0 : 1
          obj.type = 0
          obj.unit = item.items.units
          obj.chartData = {}
          obj.chartData.x = []
          obj.chartData.y = []
        }

        // obj.chartData.x.push(this.parseTime(item.lastclock))
        obj.chartData.x.push(this.parseTime(item.clock))

        obj.chartData.y.push(parseFloat(item.value_avg))
        // obj.chartData.y.push(parseFloat(item.lastvalue))
      }
      console.log(showDatas);
      let lastDateTime;
      if (ret.data.length == 0) {
        lastDateTime = new Date().getTime()
      } else {
        lastDateTime = ret.data[ret.data.length - 1].clock
      }
      this.warpData(showDatas, lastDateTime)
    },
    warpData (showDatas, lastDateTime) {

      showDatas.forEach(cpuInfo => {
        // let cpuInfo = showDatas[0]
        let dataLength = cpuInfo.chartData.x.length // 现有数据长度

        //  前边要补充的数量
        let buchong = 0
        // 应该有多少个点 
        let should = 0

        let startTime = 0
        let endTime = 0

        // 此处时刻应该是数据中的最后一个时间

        let now = new Date(lastDateTime).getTime()

        if (this.date2) {
          switch (this.date2) {
            case 86400000: // 1天 
              should = 24
              break;
            case 604800000: // 1 周
              should = 24 * 7
              break;
            case 2592000000: // 1个月
              should = 24 * 30
              break;
            case 7776000000: // 3 个月
              should = 24 * 30 * 3
              break;
          }

          startTime = now - this.date2 // 开始时间
          endTime = now

          buchong = should - dataLength // 数量

        } else {
          // 自选 的时间段
          this.queryInfo.date.beginTime = this.date1[0]

          this.queryInfo.date.endTime = this.date1[1]

          console.log(this.date1);

          startTime = this.date1[0]
          endTime = this.date1[1]
          should = (now - startTime) / 1000 / 60 / 60
          buchong = should - dataLength

          // console.log(startTime,'---------------startTime---------');
          // console.log(endTime,'---------------startTime---------');

        }

        let emptyArrX = []
        let emptyArrY = []

        console.log(buchong, '--------前面补充多少-----');

        for (let i = 0; i < buchong; i++) {
          let xValue = this.parseTime(startTime, this.DateTimeFormat())
          emptyArrX.push(xValue)
          emptyArrY.push('')
          startTime += 60 * 60 * 1000
        }



        cpuInfo.chartData.x = [...emptyArrX, ...cpuInfo.chartData.x]
        cpuInfo.chartData.y = [...emptyArrY, ...cpuInfo.chartData.y]


        // 如果所选结束时间超过了今天
        let houBuchong = 0
        if (endTime > now) {
          houBuchong = (endTime - now) / 1000 / 60 / 60
          console.log(houBuchong, '-------后面要补充多少----');

          startTime = now + 60 * 60 * 1000

          for (let i = 0; i < houBuchong; i++) {
            cpuInfo.chartData.x.push(this.parseTime(startTime, this.DateTimeFormat()))
            cpuInfo.chartData.y.push('')
            startTime += 60 * 60 * 1000
          }

        }

      })



      this.chartList = showDatas
    },


    parseTime (timeStr) {
      // let date = new Date(timeStr)
      return this.transformDateFormat(timeStr, this.DateTimeFormat())
    }

  },
  created () {

    this.queryInfo.hostId = this.$route.params.id     //接收路由跳转传参  主机id

    if (this.queryInfo.hostId) {
      sessionStorage.setItem("hostId", this.queryInfo.hostId)
    } else {
      this.queryInfo.hostId = sessionStorage.getItem('hostId')
    }

    this.checkDate()

    this.getChartData();
  }
}
</script>

<style lang='scss' scoped>
.checkDate {
  padding: 0 30px;
  height: 50px;
  margin: 0 auto;
}
</style>